package com.yunchen.server.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yunchen.server.mapper.BaseDaoMapper;
import com.yunchen.server.mapper.LoginLogsMapper;
import com.yunchen.server.pojo.Departments;
import com.yunchen.server.pojo.LoginLogs;
import com.yunchen.server.util.MyUtil;
import com.yunchen.server.util.Return;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

@Service
public class LoginLogsService {
    @Autowired
    private BaseDaoMapper baseDaoMapper;
    @Autowired
    private LoginLogsMapper loginLogsMapper;
    public void Add(Long user_id, Integer login_status, String failure_reason, HttpServletRequest request) {

        try {
            LoginLogs loginLogs=new LoginLogs();
            loginLogs.setUserId(user_id);
            String ipAddr = MyUtil.getIpAddrReal(request);
            loginLogs.setLoginIp(ipAddr);
            loginLogs.setLoginStatus(login_status);
            loginLogs.setLoginTime(new Date());
            loginLogs.setFailureReason(failure_reason);
            loginLogsMapper.insertSelective(loginLogs);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


    public Integer Count(JSONObject json) {
        String name = json.getString("name");
        String tj="";
        if (name!=null){
            if (name!=""){ tj=tj+"  and  b.name like '%"+name+"%'  "; }
        }
        String SQL="SELECT  count(a.log_id ) as mun  from login_logs a LEFT JOIN users b on a.user_id=b.user_id where 1=1 "+tj+"   ";
        Integer integer = baseDaoMapper.selectCountSql(SQL);
        return integer;
    }
    public JSONArray List (JSONObject json) {
        Integer page = json.getInteger("page");
        Integer limit = json.getInteger("limit");
        String name = json.getString("name");
        String tj="";
        if (name!=null){
            if (name!=""){ tj=tj+"  and  b.name like '%"+name+"%'  "; }
        }
        String SQL="SELECT a.*,b.`name`,b.username from login_logs a LEFT JOIN users b on a.user_id=b.user_id where 1=1 "+tj+"  ORDER BY a.log_id desc LIMIT "+(page-1)*limit+","+limit+"  ";
//        System.out.println(SQL);
        List<LinkedHashMap<String, Object>> linkedHashMaps = baseDaoMapper.selectSql(SQL);
        JSONArray listArray = JSON.parseArray(JSON.toJSONString(linkedHashMaps));
        return listArray;
    }
}
